package com.jhh.pay.weishenma.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.jhh.pay.channel.pojo.RequestBean;
import com.jhh.pay.channel.pojo.ResponseBean;
import com.jhh.pay.channel.pojo.Structure;
import com.jhh.pay.channel.pojo.Type;
import com.jhh.pay.channel.service.PayService;
import com.jhh.pay.weishenma.service.WsmService;
import com.jhh.pay.weishenma.util.DataTransferUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class WeiShenMaPayService implements PayService {
	
	private static final String CHANNEL_NAME = "WEI_SHEN_MA";
	
	@Autowired
	private WsmService wsmService;

	@Override
	public String getChannelName() {
		return CHANNEL_NAME;
	}

	@Override
	public ResponseBean pay(RequestBean request) {
		String result = wsmService.sendOrder(DataTransferUtil.transfer(request));
		ResponseBean res = null;
		String errorMsg = null;
		if (result.equals("error")) {
			res = ResponseBean.FAIL_RESPONSE();
			errorMsg = "握手成功，订单没有进入微神马程序中，订单基础字段缺失。" + "建议仔细查看订单并补全缺失的字段，并触发重发订单机制";
		} else if (result.equals("success")) {
			res = ResponseBean.SUCCESS_RESPONSE();
			errorMsg = "握手成功，订单进入wsm程序中，并开始校验，请在回调接口中查看" + "微神马返回的回调信息。" + "中间会有一小段时间，请等待。"
					+ "如果长时间没有收到回调，可以调用订单查询接口，查看订单目前状态。";
		}else {
			res = ResponseBean.FAIL_RESPONSE();
			log.warn(result);
			errorMsg = "未知的远程调用错误";
		}
		res.setMsg(errorMsg);
		return res;
	}

	@Override
	public ResponseBean deduct(RequestBean request) {
		throw new UnsupportedOperationException("微神马接口不支持扣款操作");
	}

	@Override
	public ResponseBean callbackResolve(RequestBean request) {
		request.getBody();
		ResponseBean res = ResponseBean.SUCCESS_RESPONSE();
		res.getExtension().put("ret", "success");
		return res;
	}

	@Override
	public ResponseBean state(RequestBean request) {
		wsmService.checkOrderQuery(request.getOrderNo());
		return null;
	}

	@Override
	public Structure structure(RequestBean request) {
		Structure s = new Structure();
		s.put("mid", Type.INTEGER);
		s.put("shmyc", Type.STRING);
		s.put("sendOrderUrl", Type.STRING);
		s.put("clientkeystore", Type.FILE);
		s.put("clientkeystorePassword", Type.STRING);
		s.put("cpm", Type.INTEGER);
		s.put("shmyc", Type.STRING);
		s.put("csjmsy", Type.STRING);
		return s;
	}

}
